package kr.co.handysoft.smartPolice.server.handler.info;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.zip.DataFormatException;

import kr.co.handysoft.common.compress.Archiving;
import kr.co.handysoft.common.registry.SmartPoliceRegistry;
import net.sf.json.JSONObject;

import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;

public class ClientInformationProcessHandler extends Thread {

	private BufferedReader bufferR;
	private BufferedWriter bufferW;
	private int port;
	private int localPort;
	private Socket socket;
	private InputStream is;
	private OutputStream os;
	
	public ClientInformationProcessHandler(Socket sock) {
		
		try {
			
			socket = sock;
			port = sock.getPort();
			localPort = sock.getLocalPort();
			
			System.out.println("ports : " + port + "," + localPort);
			is = sock.getInputStream();
			os = sock.getOutputStream();
			this.bufferR = new BufferedReader(new InputStreamReader(is));
			this.bufferW = new BufferedWriter(new OutputStreamWriter(os));
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {

		while(SmartPoliceRegistry.getInformationServerServiceFlag()){
		
			try {
				
				if (socket != null && !socket.isClosed()){
					
					String inputStringLine = bufferR.readLine().trim();
					
					if (inputStringLine != null && !inputStringLine.trim().equals("")){
						System.out.println("inputSringLine : " + inputStringLine);
						String deSerializer = new String(Archiving.decompress(Archiving.hexToByteArray(inputStringLine)));
						JSONObject jObj = JSONObject.fromObject(deSerializer);
						Element commandElement = (Element) XPath.selectSingleNode(SmartPoliceRegistry.getDocument(), "//informationServer/command[@id='"+jObj.getString("command")+"']");
						String classString = commandElement.getAttributeValue("class");
						System.out.println("class : " + classString);
						Class<?> tgrClass = Class.forName(classString);
						InfoServerHandler handler = (InfoServerHandler)tgrClass.newInstance();
						bufferW.write(handler.invoke(jObj.getString("body")) + "\r\n");
						bufferW.flush();
					}
				}
				
			} catch (IOException e) {
			} catch (DataFormatException e) {
			} catch (JDOMException e) {
			} catch (ClassNotFoundException e) {
			} catch (InstantiationException e) {
			} catch (IllegalAccessException e) {
			}
			
			
		}
		
	}

	public void close() {
		try {
			socket.shutdownInput();
			is.close();
			bufferR.close();
			socket.close();
			System.exit(-1);
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}

}
